<template>
  <section class="todoapp">
    
    <TodoHeader
    @addname="haddTask"
    />
    <!-- 将list通过父传子传输过去 -->
    <TodoMain 
    :list="showList"
    @delTask="delData"
    @changeTask="changeId"
    @allCheck="hcheckALL"
    />
    <TodoFooter 
    :list ="showList"
    @clearDone="hClearDone"
    @changeType="typeTask"
     />

 
  </section>
</template>

<script>
//导入数据
import  TodoHeader  from  './components/TodoHeader.vue'
import  TodoMain  from  './components/TodoMain.vue'
import  TodoFooter  from  './components/TodoFooter.vue'


export default {
  //导入组件
  components:{
    TodoHeader,
    TodoMain,
    TodoFooter
  },
  data(){
    return {
    list:JSON.parse(localStorage.getItem('list')|| '[]'),
      type:'all'
    }
  },
  methods:{
    //删除（通过id查找到该数据的下标再通过下标从数组中移除）
    delData(id){
     const index=this.list.findIndex(item=>item.id===id)
     this.list.splice(index,1)
    },
    changeId(id){
     const obj=this.list.find(item=>item.id===id)
     obj.isDone=!obj.isDone
    },
    haddTask(taskName){
      this.list.push({
        name:taskName,
        isDone:false,
        id:Date.now()
      })
    },
    hClearDone(){
      this.list=this.list.filter(item=>!item.isDone)
    },
    typeTask(type){
      this.type=type
    },
    hcheckALL(val){
    this.list.forEach(item =>item.isDone=val );
  }

  },
  //监听list数据变化
  watch:{
    list:{
      deep:true,
      handler(list){
        localStorage.setItem('list',JSON.stringify(list))
      }
    }
  },
  computed:{
    
  showList(){
    if(this.type==='all'){
  return this.list
}else if(this.type==='active'){
return this.list.filter(item =>!item.isDone)
}else if(this.type==='completed'){
return this.list.filter(item =>item.isDone)
}
}
  
    
}
}
</script>

<style></style>
